<template>
  <div
    class="common-page page-org-depts"
    v-loading.fullscreen="loading"
  >
    <div class="common-page__head">
      <!-- <comp-paths class="route" :paths="['/org', $route.fullPath]"></comp-paths> -->
      <div class="title">{{ $options.title }}</div>
    </div>
    <comp-depts
      class="common-page__body"
      ref="list"
      select
      link
      :datalist="datalist"
      :filter-params="filterParams"
      @update-data="handleListUpdate"
    >
      <template #head="scope">
        <el-row>
          <el-col
            :span="12"
            style="padding: 4px"
          >
            <el-form
              size="small"
              label-width="150px"
              inline
              @submit.native.prevent
            >
              <el-form-item label="部门名称：">
                <el-input
                  size="small"
                  v-model="filterParams.name"
                  placeholder="过滤部门"
                  @change="filterDept()"
                ></el-input>
              </el-form-item>
              <el-form-item label="对应自治区级部门：">
                <el-select
                  v-model="filterParams.belongToIdArr"
                  style="width: 240px"
                  placeholder="对应自治区级部门"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  @change="filterDept()"
                >
                  <el-option
                    v-for="data in quDepts"
                    :key="data.id"
                    :label="data.name"
                    :value="data.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col
            :span="12"
            style="padding: 4px"
          >
            <el-button
              type="plain"
              size="small"
              icon="el-icon-search"
              @click="filterDept()"
            >过滤
            </el-button>
            <el-button
              type="plain"
              size="small"
              icon="el-icon-refresh"
              @click="search()"
            >刷新列表
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="addDept()"
            >添加部门
            </el-button>
          </el-col>
        </el-row>

        <!--        <el-button-->
        <!--          type="danger"-->
        <!--          size="small"-->
        <!--          icon="el-icon-delete"-->
        <!--          @click="delDept(...scope.selects)"-->
        <!--          >删除部门</el-button-->
        <!--        >-->
      </template>
      <template #body="scope">
        <el-button
          type="plain"
          size="mini"
          @click.stop="addDept(scope.data)"
          :disabled="scope.data.level >= 5"
        >添加下级部门
        </el-button>
        <el-button
          type="primary"
          size="mini"
          @click.stop="setDept('start', scope.data)"
        >编辑
        </el-button>
        <el-button
          type="danger"
          size="mini"
          @click.stop="delDept(scope.data)"
        >删除
        </el-button>
      </template>
    </comp-depts>
    <comp-dialog
      :title="dept && dept.id ? '编辑部门' : '添加部门'"
      width="360px"
      ref="dept"
    >
      <el-form
        size="small"
        label-width="98px"
        @submit.native.prevent
        v-if="dept"
      >
        <el-form-item
          label="上级部门："
          v-if="dept.level > 1"
        >
          <!-- <template v-if="env.debug"> -->
          <template>
            <el-tag
              style="margin: 0 10px 10px 0"
              disable-transitions
              v-if="dept.dept.id"
            >{{ dept.dept.name }}
            </el-tag>
            <div v-if="dept.dept.id"></div>
            <el-button
              type="plain"
              icon="el-icon-plus"
              @click="setDept('pick-dept-start')"
            >{{ dept.dept.id ? "更换部门" : "选择部门" }}
            </el-button>
          </template>
          <!-- <span v-else>{{ dept.dept.name }}</span> -->
        </el-form-item>
        <el-form-item
          label="部门名称："
          required
        >
          <el-input
            ref="deptName"
            v-model="dept.name"
            style="width: 240px"
            placeholder="请输入"
            :maxlength="100"
            :readonly="loading"
            @change="setDept('validate')"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="部门类型："
          required
        >
          <el-select
            v-model="dept.type"
            style="width: 240px"
            placeholder="请选择"
            clearable
            @change="setDept_name('Dept_type', $event)"
          >
            <el-option
              v-for="data in env.deptTypes"
              :key="data.id"
              :label="data.name"
              :value="data.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="对应自治区级部门："
          required
          v-if="(dept.type === 'government') && dept.city.id"
        >
          <el-select
            v-model="dept.belongToId"
            style="width: 240px"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="data in quDepts"
              :key="data.id"
              :label="data.name"
              :value="data.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在地区：">
          <el-select
            v-model="dept.province.id"
            style="margin-bottom: 10px; width: 240px"
            placeholder="省份"
            clearable
            @change="setDept('validate', $event)"
          >
            <el-option
              v-for="data in provinces"
              :key="data.id"
              :label="data.name"
              :value="data.id"
            ></el-option>
          </el-select>
          <el-select
            v-model="dept.city.id"
            style="margin-bottom: 10px; width: 240px"
            placeholder="城市"
            clearable
            @change="setDept('validate')"
          >
            <template v-for="data in citys">
              <el-option
                :key="data.id"
                :label="data.name"
                :value="data.id"
                v-if="data.province.id === dept.province.id"
              ></el-option>
            </template>
          </el-select>
          <el-select
            v-model="dept.county.id"
            style="width: 240px"
            placeholder="县区"
            clearable
            @change="setDept('validate')"
          >
            <template v-for="data in countys">
              <el-option
                :key="data.id"
                :label="data.name"
                :value="data.id"
                v-if="data.city.id === dept.city.id"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="排序值：">
          <el-input
            v-model="dept.sort"
            style="width: 160px"
            placeholder="请输入"
            :readonly="loading"
            @change="setDept('validate')"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-check"
            @click="setDept('submit')"
          >{{ dept.id ? "保存" : "添加" }}
          </el-button>
          <el-button
            type="plain"
            icon="el-icon-close"
            @click="setDept('end')"
          >放弃
          </el-button>
        </el-form-item>
      </el-form>
    </comp-dialog>
    <comp-dialog
      title="选择部门"
      width="720px"
      height="80vh"
      ref="deptPicker"
    >
      <comp-depts
        style="height: 100%"
        ref="deptPickerList"
        v-if="dept"
      >
        <template #body="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-check"
            @click.stop="setDept('pick-dept-end', scope.data)"
          >选择
          </el-button>
        </template>
        <template #foot="scope">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="setDept('pick-dept-end')"
          >放弃
          </el-button>
        </template>
      </comp-depts>
    </comp-dialog>
  </div>
</template>

<script>
import mixin from "../mixin";
import {string, int, deepCopy} from "../util";
import {deptApi} from "@/api/dept";

export default {
  name: "page-org-depts",
  title: "部门管理",
  nodes: ["/menu/org"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    dept: null,
    provinces: [],
    citys: [],
    countys: [],
    datalist: null,
    deptCopy: null,
    //部门名称
    Dept_name: null,
    //省名称
    provincename: null,
    //市名称
    cityname: null,
    //区名称
    countyname: null,
    disposeform: null,
    filterValue: '',
    filterParams: {
      name: null,
      belongToIdArr: [],
    },
    quDepts: [],// 区直部门，选归属部门的
  }),
  methods: {
    setDept_name(name, data) {
      let selectname = data === "office" ? "服务专员" : "职能部门";
      // console.log("selectname", selectname);
      this.Dept_name = selectname;
    },
    search() {
      if (this.loading) return;
      this.$nextTick(() => this.$refs.list.init());
    },
    miniUpdateList() {
      if (this.loading) return;
      this.$nextTick(() => this.$refs.list.miniUpdateList(this.dept.id));
    },
    addDept(dept) {
      console.log("dept", dept);
      if (this.loading) return;
      let target = this.plugins.user.formatDept();

      this.quDepts = this.$refs.list?.list?.filter(x => x.parentId === '202216425835730001')

      if (dept) {
        target.dept.id = dept.id;
        target.dept.name = dept.name;
        target.level = dept.level + 1;
      } else {
        target.level = 1;
      }
      this.setDept("start", target);
    },
    setDept(action, data, select) {
      if (this.loading) return;

      let form = this.dept;
      let provinces = this.provinces;
      let citys = this.citys;
      let countys = this.countys;
      if (!action || action === "start") {
        // this.quDepts = this.$refs.list?.list?.filter(x => x.parentId === '202216425835730001')
       deptApi.getCorrespondingDept().then(res => {
          this.quDepts =res.data.map(x=>{
            return {
              id:x.deptId,
              name:x.deptName,
              ...x
            }
          })
        })
        this.dept = deepCopy(data);
        this.deptCopy = JSON.parse(JSON.stringify(data));
        this.provinces = this.plugins.user.provinces;
        this.citys = this.plugins.user.citys;
        this.countys = this.plugins.user.countys;
        if(data.id){
          deptApi.getDept(data.id || data.dept?.id).then(res => {
            this.dept = {
              ...res.data,
              id: res.data.deptId,
              name: res.data.deptName,
              province:{
                id: res.data.provinceId
              },
              city:{
                id: res.data.cityId
              },
              county:{
                id: res.data.areaId
              },
              type: res.data.deptType == "2"?'office':'government',
            }

            this.setDept("validate");
            this.$refs.dept.init();
            this.$nextTick(() => this.$refs.deptName.focus());
          })
        }else{
          this.$refs.dept.init();
          this.$nextTick(() => this.$refs.deptName.focus());
        }

      } else if (action === "validate") {
        let error = "";
        form.name = string(form.name).trim();
        form.province.id = string(
          () =>
            provinces.find((province) => province.id === form.province.id).id
        );
        this.provincename = string(
          () =>
            provinces.find((province) => province.id === form.province.id).name
        );

        form.city.id = string(
          () =>
            citys.find(
              (city) =>
                city.id === form.city.id &&
                city.province.id === form.province.id
            ).id
        );
        this.cityname = string(
          () =>
            citys.find(
              (city) =>
                city.id === form.city.id &&
                city.province.id === form.province.id
            ).name
        );

        form.county.id = string(
          () =>
            countys.find(
              (county) =>
                county.id === form.county.id && county.city.id === form.city.id
            ).id
        );
        this.countyname = string(
          () =>
            countys.find(
              (county) =>
                county.id === form.county.id && county.city.id === form.city.id
            ).name
        );
        if (form.type === 'government' && form.city?.id) {
          error = error || (form.belongToId ? "" : "请选择对应自治区级部门！");
        }

        error = error || (form.name ? "" : "请输入部门名称！");
        error = error || (form.type ? "" : "请选择部门类型！");
        form.sort = Math.max(int(form.sort), 0) || null;
        if (data) this.plugins.modal.toast(error, "error");
        return !error;
      } else if (action === "pick-dept-start") {
        this.$refs.deptPicker.init();
        this.$nextTick(() => this.$refs.deptPickerList.init());
      } else if (action === "pick-dept-end") {
        console.log(form.id);
        if (form.id == data.id) {
          this.plugins.modal.alert("警告", "更改部门不能选择自己为部门", "error");
        } else {
          if (data) form.dept = data;
          this.$refs.deptPicker.close();
          this.setDept("validate");
        }


      } else if (action === "submit") {
        if (!this.setDept("validate", true)) return;
        else this.loading = true;
        if (form.id) {
          form.activated = false;
          this.plugins.user.setDept(form).then((res) => {
            if (this.Dept_name) form.typeText = this.Dept_name;
            if (this.provincename) form.province.name = this.provincename;
            if (this.cityname) form.city.name = this.cityname;
            if (this.countyname) form.county.name = this.countyname;
            console.log("form_____", form);
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("保存成功！", "success");
              this.setDept("end");
              this.miniUpdateList();
              this.datalist = form.id;
              let b = this.$refs.list.list;
              // this.jiexi(b, form);
              console.log("b:", b);
              // this.$forceUpdate();
              // this.datalist = b;
              // this.plugins.user.getDepts({ deptId: form.id, linage: 1000, page: 1 }).then((res) => {
              //     console.log(res);
              //     if (res.code === 0) {
              //        this.datalist = res
              //     }
              // });
            } else {
              this.plugins.modal.alert(
                "保存失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
        } else
          this.plugins.user.addDept(form).then((res) => {
            form.id = res.data;
            if (this.Dept_name) form.typeText = this.Dept_name;
            if (this.provincename) form.province.name = this.provincename;
            if (this.cityname) form.city.name = this.cityname;
            if (this.countyname) form.county.name = this.countyname;
            form.activated = false;
            console.log("addform", form);
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("添加成功！", "success");
              this.setDept("end");
              this.datalist = form.id;
              let b = this.$refs.list.list;
              form.activated = false;
              // this.jiexi2(b, form);
              this.$forceUpdate();
              this.search();
            } else {
              this.plugins.modal.alert(
                "添加失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
      } else if (action === "end") {
        this.$refs.dept.close();
      }
    },
    delDept(...depts) {
      if (this.loading) return;
      if (depts.length === 0)
        return this.plugins.modal.toast("请先勾选要删除的部门哦！", "warning");
      let content =
        " <span style='color:red;'>" +
        (depts.length > 1
          ? "勾选的" + depts.length + "个部门"
          : depts[0].name) +
        "</span> 吗？";
      this.plugins.modal
        .alert("删除确认", "确定删除" + content, "warning", [
          "确定删除",
          "再想想",
        ])
        .then((ok) => {
          if (!ok) return;
          this.loading = true;
          this.plugins.user.delDept(...depts.reverse()).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("删除成功！", "success");
              this.search();
            } else {
              this.plugins.modal.alert(
                "删除失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
        });
    },
    jiexi(list, data) {
      console.log("list", list);
      console.log("jiexi", data);
      const deptId = data.dept.id;
      for (let i in list) {
        list[i]["activated"] = false;
        if (this.deptCopy.dept.id != deptId) {
          if (deptId === list[i].id) {
            list[i].depts.push(data);
          }
        }
        if (list[i].id === data.id) {
          if (deptId && list[i].dept.id != deptId) {
            list.splice(i, 1);
          } else {
            list[i] = data;
          }
          break;
        } else {
          if (list[i].expanded) {
            this.jiexi(list[i].depts, data);
          }
        }
      }
    },
    jiexi2(list, data) {
      console.log("list", list);
      console.log("jiexi2data", data);
      const deptId = data.dept.id;
      for (let i in list) {
        if (deptId === list[i].id) {
          list[i].depts.push(data);
        } else {
          if (list[i].expanded) {
            this.jiexi2(list[i].depts, data);
          }
        }
      }
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    filterDept() {
      this.$nextTick(() => this.$refs.list.filterDept());
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user
        .call(async () => {
          let res = await this.plugins.user.init();
          if (res.code === 0) {
          }
          return res;
        })
        .then((res) => {
          this.loading = false;
          this.$root.$refs.navbar.init();
          if (res.code === 0) {
            if (this.access(this.$route.name)) {
              this.search();
            } else {
              this.$router.replace("/home");
            }
          } else if (res.code === 2) {
            this.$root.$refs.navbar.login();
          } else {
            this.plugins.modal
              .alert("页面加载失败", res.code + "：" + res.msg, "error")
              .then(() => this.$router.replace("/home"));
          }
        });
    },
    handleListUpdate() {
      console.log('列表刷新数据')
      this.quDepts = this.$refs.list?.list?.filter(x => x.parentId === '202216425835730001')
    }
  },
  watch: {
    Dept_name(newVal) {
    },
  },
};
</script>

<style lang="scss">
.page-org-depts {
  overflow: hidden;
}
</style>
